package ThreadWorker;
/**
* @author 李涛
* @version 创建时间：2018年8月26日 下午6:26:40
* 类说明
*/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadWorker {

	/**
	 * 适合少量任务
	 */
	private ExecutorService exc = Executors.newCachedThreadPool();
	private CompletionService<HashMap<String, Object>> sc = new ExecutorCompletionService<>(exc);
	private List<Worker> works = new ArrayList<>();
	private int workLength;

	public void put(Worker worker) {
		works.add(worker);
		workLength++;
	}

	public void start() {
		for (Worker w : works) {
			sc.submit(w);
		}
	}

	/**
	 * 阻塞获取
	 * 
	 * @param key
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public Object get(String key) throws InterruptedException, ExecutionException {
		for (int i = 0; i < workLength; i++) {
			Future<HashMap<String, Object>> f = sc.take();
			if (f != null) {
				HashMap<String, Object> result = f.get();
				if (result.containsKey(key)) {
					return result.get(key);
				}
			}
		}
		return key;
	}

	/**
	 * 自行判断快速执行，减少CPU等待时间
	 * 
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public List<HashMap<String, Object>> getAll() throws InterruptedException, ExecutionException {
		List<HashMap<String, Object>> allList = new ArrayList<>();
		for (int i = 0; i < workLength; i++) {
			Future<HashMap<String, Object>> f = sc.take();
			if (f != null) {
				HashMap<String, Object> result = f.get();
				allList.add(result);
			}
		}
		return allList;
	}
}


